using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ERP.RepositoryManage;
using ERP.RepositoryManage.Dtos;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace ERP.Web.Controllers
{
    public class ProcurementController : Controller
    {
        private readonly IProcurementService _procurementService;
        private readonly ILogger<ProcurementController> _logger;

        public ProcurementController(
            IProcurementService procurementService,
            ILogger<ProcurementController> logger)
        {
            _procurementService = procurementService;
            _logger = logger;
        }

        /// <summary>
        /// 采购入库管理页面
        /// </summary>
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 采购入库添加/编辑页面
        /// </summary>
        public IActionResult AddEdit(int? id)
        {
            ViewBag.Id = id;
            return View();
        }

        /// <summary>
        /// 入库明细查看页面
        /// </summary>
        public IActionResult Details(int id)
        {
            ViewBag.Id = id;
            return View();
        }

        /// <summary>
        /// 添加入库明细页面
        /// </summary>
        public IActionResult AddDetail(int procurementId)
        {
            ViewBag.ProcurementId = procurementId;
            return View();
        }

        /// <summary>
        /// 供应商选择页面
        /// </summary>
        public IActionResult SupplierSelect()
        {
            return View();
        }

        /// <summary>
        /// 物料选择页面
        /// </summary>
        public IActionResult MaterialSelect()
        {
            return View();
        }

        /// <summary>
        /// 获取采购入库列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetProcurements(GetProcurementInputDto input)
        {
            try
            {
                _logger.LogInformation("获取采购入库列表，参数: {@Input}", input);
                var result = await _procurementService.GetListAsync(input);

                return Json(new
                {
                    code = 0,
                    msg = "",
                    count = result.TotalCount,
                    data = result.Items
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取采购入库列表失败");
                return Json(new
                {
                    code = 500,
                    msg = ex.Message,
                    count = 0,
                    data = new List<ProcurementDto>()
                });
            }
        }

        /// <summary>
        /// 获取采购入库详情
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetProcurement(int id)
        {
            try
            {
                _logger.LogInformation("获取采购入库详情，ID: {Id}", id);
                var result = await _procurementService.GetAsync(id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取采购入库详情失败，ID: {Id}", id);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 生成入库单编号
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GenerateInboundCode()
        {
            try
            {
                var code = await _procurementService.GenerateInboundCodeAsync();
                _logger.LogInformation("生成入库单编号: {Code}", code);
                return Json(new { success = true, code = code });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成入库单编号失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 创建采购入库
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> CreateProcurement(CreateProcurementDto input)
        {
            _logger.LogInformation("创建采购入库，参数: {@Input}", input);

            if (!ModelState.IsValid)
            {
                var errors = string.Join("; ", ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage));
                _logger.LogWarning("创建采购入库参数验证失败: {Errors}", errors);
                return Json(new { success = false, message = errors });
            }

            try
            {
                var result = await _procurementService.CreateAsync(input);
                _logger.LogInformation("创建采购入库成功，ID: {Id}", result.Id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建采购入库失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 更新采购入库
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> UpdateProcurement(UpdateProcurementDto input)
        {
            _logger.LogInformation("更新采购入库，参数: {@Input}", input);

            if (!ModelState.IsValid)
            {
                var errors = string.Join("; ", ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage));
                _logger.LogWarning("更新采购入库参数验证失败: {Errors}", errors);
                return Json(new { success = false, message = errors });
            }

            try
            {
                var result = await _procurementService.UpdateAsync(input.Id, input);
                _logger.LogInformation("更新采购入库成功，ID: {Id}", input.Id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新采购入库失败，ID: {Id}", input.Id);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 删除采购入库
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> DeleteProcurement(int id)
        {
            _logger.LogInformation("删除采购入库，ID: {Id}", id);

            try
            {
                await _procurementService.DeleteAsync(id);
                _logger.LogInformation("删除采购入库成功，ID: {Id}", id);
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除采购入库失败，ID: {Id}", id);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 执行入库操作
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> ExecuteInbound(int id)
        {
            _logger.LogInformation("执行入库操作，ID: {Id}", id);

            try
            {
                // 获取当前状态
                var procurement = await _procurementService.GetAsync(id);
                int currentStatus = procurement.DocumentStatus;
                
                await _procurementService.ExecuteInboundAsync(id);
                
                // 获取执行后的状态
                procurement = await _procurementService.GetAsync(id);
                int newStatus = procurement.DocumentStatus;
                
                string message = currentStatus == 0 ? "已修改状态为待入库" : "入库操作成功";
                
                _logger.LogInformation("执行入库操作成功，ID: {Id}, 状态从 {OldStatus} 变为 {NewStatus}", 
                    id, currentStatus, newStatus);
                    
                return Json(new { success = true, message = message, newStatus = newStatus });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "执行入库操作失败，ID: {Id}", id);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取入库明细列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetDetails(int procurementId)
        {
            try
            {
                _logger.LogInformation("获取入库明细列表，采购入库ID: {ProcurementId}", procurementId);
                var result = await _procurementService.GetDetailsAsync(procurementId);
                
                _logger.LogInformation("获取入库明细成功，数量: {Count}", result?.Count ?? 0);

                return Json(new
                {
                    code = 0,
                    msg = "",
                    data = result ?? new List<ProcurementDetailDto>()
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取入库明细列表失败，采购入库ID: {ProcurementId}", procurementId);
                return Json(new
                {
                    code = 500,
                    msg = ex.Message,
                    data = new List<ProcurementDetailDto>()
                });
            }
        }

        /// <summary>
        /// 添加入库明细
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> AddDetail(CreateProcurementDetailDto input)
        {
            _logger.LogInformation("添加入库明细，参数: {@Input}", input);

            if (!ModelState.IsValid)
            {
                var errors = string.Join("; ", ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage));
                _logger.LogWarning("添加入库明细参数验证失败: {Errors}", errors);
                return Json(new { success = false, message = errors });
            }

            try
            {
                var result = await _procurementService.AddDetailAsync(input);
                _logger.LogInformation("添加入库明细成功，ID: {Id}", result.Id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加入库明细失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 删除入库明细
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> DeleteDetail(int detailId)
        {
            _logger.LogInformation("删除入库明细，ID: {DetailId}", detailId);

            try
            {
                await _procurementService.DeleteDetailAsync(detailId);
                _logger.LogInformation("删除入库明细成功，ID: {DetailId}", detailId);
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除入库明细失败，ID: {DetailId}", detailId);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取供应商选择列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetSupplierSelect(GetSupplierSelectInputDto input)
        {
            try
            {
                _logger.LogInformation("获取供应商选择列表，参数: {@Input}", input);
                var result = await _procurementService.GetSupplierSelectListAsync(input);

                return Json(new
                {
                    code = 0,
                    msg = "",
                    count = result.TotalCount,
                    data = result.Items
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取供应商选择列表失败");
                return Json(new
                {
                    code = 500,
                    msg = ex.Message,
                    count = 0,
                    data = new List<SupplierSelectDto>()
                });
            }
        }

        /// <summary>
        /// 获取物料选择列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetMaterialSelect(GetMaterialSelectInputDto input)
        {
            try
            {
                _logger.LogInformation("获取物料选择列表，参数: {@Input}", input);
                var result = await _procurementService.GetMaterialSelectListAsync(input);

                return Json(new
                {
                    code = 0,
                    msg = "",
                    count = result.TotalCount,
                    data = result.Items
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取物料选择列表失败");
                return Json(new
                {
                    code = 500,
                    msg = ex.Message,
                    count = 0,
                    data = new List<MaterialSelectDto>()
                });
            }
        }

        /// <summary>
        /// 获取物料类型树
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetMaterialTypeTree()
        {
            try
            {
                var result = await _procurementService.GetMaterialTypeTreeAsync();
                _logger.LogInformation("获取物料类型树成功");
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取物料类型树失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取仓库选择列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetWarehouseSelect()
        {
            try
            {
                _logger.LogInformation("获取仓库选择列表");
                var result = await _procurementService.GetWarehouseSelectListAsync();
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取仓库选择列表失败");
                return Json(new { success = false, message = ex.Message });
            }
        }
    }
} 